package com.reservation.controller;

import com.reservation.common.ApiResponse;
import com.reservation.dto.ProductDTO;
import com.reservation.dto.ProductRequest;
import com.reservation.service.ProductService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 商品控制器
 */
@Slf4j
@RestController
@RequestMapping("/products")
@RequiredArgsConstructor
public class ProductController {

    private final ProductService productService;

    /**
     * 获取所有商品
     */
    @GetMapping
    public ApiResponse<List<ProductDTO>> getAllProducts() {
        log.info("获取所有商品列表");
        try {
            List<ProductDTO> products = productService.getAllProducts();
            return ApiResponse.success("获取商品列表成功", products);
        } catch (Exception e) {
            log.error("获取商品列表失败", e);
            return ApiResponse.error("获取商品列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取有库存的商品
     */
    @GetMapping("/available")
    public ApiResponse<List<ProductDTO>> getAvailableProducts() {
        log.info("获取有库存的商品列表");
        try {
            List<ProductDTO> products = productService.getAvailableProducts();
            return ApiResponse.success("获取有库存商品列表成功", products);
        } catch (Exception e) {
            log.error("获取有库存商品列表失败", e);
            return ApiResponse.error("获取有库存商品列表失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID获取商品
     */
    @GetMapping("/{id}")
    public ApiResponse<ProductDTO> getProductById(@PathVariable Long id) {
        log.info("根据ID获取商品: {}", id);
        try {
            return productService.getProductById(id)
                    .map(product -> ApiResponse.success("获取商品成功", product))
                    .orElse(ApiResponse.notFound("商品不存在"));
        } catch (Exception e) {
            log.error("获取商品失败: id={}", id, e);
            return ApiResponse.error("获取商品失败: " + e.getMessage());
        }
    }

    /**
     * 搜索商品
     */
    @GetMapping("/search")
    public ApiResponse<List<ProductDTO>> searchProducts(@RequestParam String name) {
        log.info("搜索商品: name={}", name);
        try {
            List<ProductDTO> products = productService.searchProductsByName(name);
            return ApiResponse.success("搜索商品成功", products);
        } catch (Exception e) {
            log.error("搜索商品失败: name={}", name, e);
            return ApiResponse.error("搜索商品失败: " + e.getMessage());
        }
    }

    /**
     * 检查库存
     */
    @GetMapping("/{id}/stock")
    public ApiResponse<Boolean> checkStock(@PathVariable Long id, @RequestParam Integer quantity) {
        log.info("检查库存: productId={}, quantity={}", id, quantity);
        try {
            boolean hasStock = productService.checkStock(id, quantity);
            return ApiResponse.success("检查库存成功", hasStock);
        } catch (Exception e) {
            log.error("检查库存失败: productId={}, quantity={}", id, quantity, e);
            return ApiResponse.error("检查库存失败: " + e.getMessage());
        }
    }

    /**
     * 获取库存不足的商品
     */
    @GetMapping("/low-stock")
    public ApiResponse<List<ProductDTO>> getLowStockProducts(@RequestParam(defaultValue = "5") Integer threshold) {
        log.info("获取库存不足的商品: threshold={}", threshold);
        try {
            List<ProductDTO> products = productService.getLowStockProducts(threshold);
            return ApiResponse.success("获取库存不足商品成功", products);
        } catch (Exception e) {
            log.error("获取库存不足商品失败: threshold={}", threshold, e);
            return ApiResponse.error("获取库存不足商品失败: " + e.getMessage());
        }
    }

    /**
     * 新增商品
     */
    @PostMapping
    public ApiResponse<ProductDTO> createProduct(@Valid @RequestBody ProductRequest request) {
        log.info("新增商品请求: name={}", request.getName());
        try {
            ProductDTO product = productService.createProduct(request);
            return ApiResponse.success("新增商品成功", product);
        } catch (Exception e) {
            log.error("新增商品失败: name={}", request.getName(), e);
            return ApiResponse.error("新增商品失败: " + e.getMessage());
        }
    }

    /**
     * 编辑商品
     */
    @PutMapping("/{id}")
    public ApiResponse<ProductDTO> updateProduct(@PathVariable Long id, @Valid @RequestBody ProductRequest request) {
        log.info("编辑商品请求: id={}, name={}", id, request.getName());
        try {
            ProductDTO product = productService.updateProduct(id, request);
            return ApiResponse.success("编辑商品成功", product);
        } catch (Exception e) {
            log.error("编辑商品失败: id={}, name={}", id, request.getName(), e);
            return ApiResponse.error("编辑商品失败: " + e.getMessage());
        }
    }

    /**
     * 删除商品
     */
    @DeleteMapping("/{id}")
    public ApiResponse<String> deleteProduct(@PathVariable Long id) {
        log.info("删除商品请求: id={}", id);
        try {
            productService.deleteProduct(id);
            return ApiResponse.success("删除商品成功", "success");
        } catch (Exception e) {
            log.error("删除商品失败: id={}", id, e);
            return ApiResponse.error("删除商品失败: " + e.getMessage());
        }
    }

    /**
     * 批量删除商品
     */
    @DeleteMapping("/batch")
    public ApiResponse<String> deleteProducts(@RequestBody List<Long> ids) {
        log.info("批量删除商品请求: ids={}", ids);
        try {
            productService.deleteProducts(ids);
            return ApiResponse.success("批量删除商品成功", "success");
        } catch (Exception e) {
            log.error("批量删除商品失败: ids={}", ids, e);
            return ApiResponse.error("批量删除商品失败: " + e.getMessage());
        }
    }
}
